// components/global-login-modal/global-login-modal.js
Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },

  data: {
    isLoading: false,
    customNickname: '',
    wxUserInfo: null,
    wxCode: null,
    inputMethod: 'custom',
    presetNicknames: ['妈妈', '爸爸','哥哥', '姐姐', '弟弟', '妹妹']
  },

  lifetimes: {
    attached() {
      // 监听键盘状态
      this.setupKeyboardListener();
    },
    
    detached() {
      // 清理键盘监听
      this.cleanupKeyboardListener();
    }
  },

  methods: {
    // 设置键盘监听
    setupKeyboardListener() {
      // 监听键盘弹出
      wx.onKeyboardHeightChange((res) => {
        if (res.height > 0) {
          // 键盘弹出
          this.setData({
            isKeyboardOpen: true
          });
        } else {
          // 键盘收起
          this.setData({
            isKeyboardOpen: false
          });
        }
      });
    },

    // 清理键盘监听
    cleanupKeyboardListener() {
      wx.offKeyboardHeightChange();
    },

    // 关闭弹框
    onClose() {
      this.triggerEvent('close');
    },

    // 切换到自定义输入
    switchToCustom() {
      this.setData({
        inputMethod: 'custom'
      });
    },

    // 切换到预设昵称
    switchToPreset() {
      this.setData({
        inputMethod: 'preset'
      });
    },

    // 选择预设昵称
    selectPresetNickname(e) {
      const nickname = e.currentTarget.dataset.nickname;
      this.setData({
        customNickname: nickname
      });
    },

    // 输入昵称
    onNicknameInput(e) {
      this.setData({
        customNickname: e.detail.value
      });
    },

    stopPropagation() {},

    handleLogin() {
      if (!this.data.customNickname || this.data.customNickname.length < 2) {
        wx.showToast({
          title: '昵称至少2个字符',
          icon: 'none'
        })
        return
      }

      this.setData({ isLoading: true })
      this.getUserInfoAndLogin()
    },

    getUserInfoAndLogin() {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          this.setData({ wxUserInfo: res.userInfo })
          this.wxLogin(res.userInfo)
        },
        fail: (err) => {
          if (err.errMsg.includes('getUserProfile:fail auth deny')) {
            wx.showModal({
              title: '需要授权',
              content: '为了提供更好的服务，需要获取您的头像和昵称信息',
              confirmText: '重新授权',
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  this.getUserInfoAndLogin()
                } else {
                  this.setData({ isLoading: false })
                }
              }
            })
          } else {
            wx.showToast({ title: '获取用户信息失败', icon: 'none' })
            this.setData({ isLoading: false })
          }
        }
      })
    },

    wxLogin(userInfo) {
      wx.login({
        success: (res) => {
          if (res.code) {
            this.setData({ wxCode: res.code })
            this.createUserAndLogin(userInfo, res.code)
          } else {
            this.setData({ isLoading: false })
            wx.showToast({ title: '微信登录失败', icon: 'none' })
          }
        },
        fail: (err) => {
          this.setData({ isLoading: false })
          wx.showToast({ title: '微信登录失败', icon: 'none' })
        }
      })
    },

    // 创建用户并登录
    async createUserAndLogin(userInfo, code) {
      try {
        const app = getApp()
        
        // 调用应用的登录方法
        const loginResult = await app.handleWxLogin(userInfo, code, this.data.customNickname)
        
        if (loginResult.success) {
          // 根据是否是新用户显示不同的提示
          if (loginResult.isNewUser) {
            wx.showToast({
              title: '注册成功，欢迎加入！',
              icon: 'success'
            })
          } else {
            wx.showToast({
              title: '登录成功，欢迎回来！',
              icon: 'success'
            })
          }
          
          // 登录成功后关闭弹框并通知父组件
          this.triggerEvent('loginSuccess')
          this.onClose()
          this.refreshCurrentPage()
        } else {
          wx.showToast({
            title: loginResult.error || '登录失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('创建用户失败:', error)
        wx.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })
      } finally {
        this.setData({ isLoading: false })
      }
    },

    refreshCurrentPage() {
      const app = getApp()
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      
      if (currentPage && currentPage.onLoginSuccess) {
        currentPage.onLoginSuccess()
      }
      
      if (app.globalData.eventBus) {
        app.globalData.eventBus.emit('userLoginSuccess')
      }
    }
  }
}) 